package com.burton.dp;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CreateNodeBackground {

	private static String ZOOKEEPER_SERVER_STRING = "127.0.0.1:2181";

	static CountDownLatch semaphore = new CountDownLatch(2);
	static ExecutorService tp = Executors.newFixedThreadPool(2);
	static String path = "/zk";

	public static void main(String[] args) throws Exception {
		CuratorFramework client = CuratorFrameworkFactory
				.builder()
				.connectString(ZOOKEEPER_SERVER_STRING)
				.sessionTimeoutMs(5000)
				.namespace("base")
				.retryPolicy(
						new ExponentialBackoffRetry(5000, Integer.MAX_VALUE))
				.build();
		client.start();
		System.out.println("Main thread " + Thread.currentThread().getName());
		client.create().creatingParentsIfNeeded()
				.withMode(CreateMode.EPHEMERAL)
				.inBackground(new BackgroundCallback() {
					public void processResult(CuratorFramework client,
							CuratorEvent event) throws Exception {
						System.out.println("event code:"
								+ event.getResultCode() + ";type:"
								+ event.getType());
						System.out.println("thread of processResult:"
								+ Thread.currentThread().getName());
						semaphore.countDown();
					}
				}, tp).forPath(path);
		semaphore.await();
		tp.shutdown();
	}

}
